package org.absolutezero.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Version;


@Entity
public class SearchResult implements Serializable{
	
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	    
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Integer getVersion() {
		return version;
	}

	public void setVersion(Integer version) {
		this.version = version;
	}

	@Version
	private Integer version;
	
	@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="recipe_id")
	private Recipe recipe;
		
	private Integer totalCost;
	
	private Integer matchPercent;

	public Recipe getRecipe() {
		return recipe;
	}

	public void setRecipe(Recipe recipe) {
		this.recipe = recipe;
	}

	public Integer getTotalCost() {
		return totalCost;
	}

	public void setTotalCost(Integer totalCost) {
		this.totalCost = totalCost;
	}

	public Integer getMatchPercent() {
		return matchPercent;
	}

	public void setMatchPercent(Integer matchPercent) {
		this.matchPercent = matchPercent;
	}

	
	
	
	public void persist() {
    	
		
	    EntityManager em = entityManager();
	    try{
	    	
	      EntityTransaction tx  = em.getTransaction();
 	      tx.begin();
 	  
 	      Recipe r = em.merge(this.recipe);
 	      SearchResult s = em.merge(this);
 	      
	      em.persist(s);
	      tx.commit();
	     
	    } catch(Exception e){
	    	
	    }
	    
	    finally {
	      em.close();
	    }
	  }

	public void remove() {
	    EntityManager em = entityManager();
	    try {
	      SearchResult attached = em.find(SearchResult.class, this.id);
	      EntityTransaction tx  = em.getTransaction();
		      tx.begin();
	      em.remove(attached);
	      tx.commit();
	    } finally {
	      em.close();
	    }
 	}

	public static SearchResult findSearchResult(Long id){
			if (id == null) {
				      return null;
		    }
		    EntityManager em = entityManager();
		    try {
		      SearchResult s = em.find(SearchResult.class, id);
		      return s;
		    } finally {
		      em.close();
		    }
		}

	private static EntityManager entityManager(){
	 	return EMF.get().createEntityManager();
	 }
}


